package niu.fencer.tool.qrcode.ui;



import android.content.Context;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import java.util.Locale;
import java.util.Set;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import niu.fencer.tool.qrcode.R;
import niu.fencer.tool.qrcode.activity.MainActivity;
import niu.fencer.tool.qrcode.activity.QrCodeGenActivity;
import niu.fencer.tool.qrcode.util.FileUtil;
import niu.fencer.tool.qrcode.util.LogUtil;

/**
 * @Author: wuchaowen
 * @Description:
 * @Time:
 **/
public class FileItemAdapter extends RecyclerView.Adapter<FileItemViewHolder> implements Comparator<File> {

    private final FileItemRefData.Options _dopt;
    private final List<File> _adapterData; // List of current folder
    private final Set<File> _currentSelection;
    private File _currentFolder;
    private final Context _context;
    FragmentFile fragment;


    public FileItemAdapter(FragmentFile fragment, Context context,File folder) {
        this.fragment=fragment;

        _dopt = new   FileItemRefData.Options();;
        _adapterData = new ArrayList<>();

        _currentSelection = new HashSet<>();
        _context = context.getApplicationContext();
//        file=FileItemAdapter.this._context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        loadFolder(folder);
    }
    @Override
    public int getItemViewType(final int position) {
        return R.layout.fragment_file_item;
    }
    @NonNull
    @Override
    public FileItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
        return new  FileItemViewHolder(v);
    }
    @Override
    public int getItemCount() {return _adapterData.size();}
    @Override
    public void onBindViewHolder(@NonNull FileItemViewHolder holder, int position) {
        Log.i("9527",position+"onBindViewHolder_adapterData:\n"+_adapterData);
        File file_pre = _adapterData.get(position);
        if (file_pre == null) {
            holder.title.setText("????");
            return;
        }

        final File file_pre_Parent = file_pre.getParentFile() == null ? new File("/") : file_pre.getParentFile();
        final String filename = file_pre.getName();
        final File file = file_pre;
        final File fileParent = file.getParentFile() == null ? new File("/") : file.getParentFile();

        final boolean isGoUp = file.equals(_currentFolder.getParentFile());

        holder.title.setText(isGoUp ? ".." : filename, TextView.BufferType.SPANNABLE);
        holder.image.setImageResource(file.isFile()?  _dopt.fileImage:_dopt.folderImage);
        String lastModify=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(file_pre.lastModified()));;
        holder.description.setText( FileUtil.getFileSize(file)+" "+lastModify);

        if (_dopt.itemSidePadding > 0) {
            int dp = (int) (_dopt.itemSidePadding * _context.getResources().getDisplayMetrics().density);
            holder.itemRoot.setPadding(dp, holder.itemRoot.getPaddingTop(), dp, holder.itemRoot.getPaddingBottom());
        }
        holder.itemRoot.setContentDescription(holder.title.getText().toString() + " " + holder.description.getText().toString());
        holder.itemRoot.setOnClickListener(view->{
            File f = FileItemAdapter.this._adapterData.get(position);
            LogUtil.i("itemRoot.setOnClickListener"+f.getAbsolutePath());
            if (f.isDirectory()) {
                loadFolder(f);
            } else {
                Bundle args = new Bundle();
                args.putBoolean(MainActivity.IS_FILE,true);
                args.putString(MainActivity.QRCODE_SOURCE,f.getAbsolutePath());
                MainActivity act=(MainActivity)FileItemAdapter.this.fragment.getActivity();
                act.switchTab(R.id.navigation_text,args);
            }
        });
        if(file.isFile()){//qrcode
            holder.genButton.setVisibility(View.VISIBLE);
            holder.genButton.setOnClickListener(view->{
                MainActivity act=(MainActivity)FileItemAdapter.this.fragment.getActivity();
                startQRCode(act,true,file.getAbsolutePath());
            });
        }else{
            holder.genButton.setVisibility(View.INVISIBLE);
        }
    }

    private void startQRCode(MainActivity act , boolean isFile, String source){
        Intent intent = new Intent(act, QrCodeGenActivity.class);
        intent.putExtra(MainActivity.IS_FILE,isFile);
        intent.putExtra(MainActivity.QRCODE_SOURCE,source);
        act.startActivity(intent);
    }

    public void loadFolder(final File folder) {
        final Handler handler = new Handler();
        _currentSelection.clear();
        Thread t=new Thread()
        {
            @Override
            public void run() {
                {
                    _currentFolder = folder;
                    _adapterData.clear();

                    File file;
                    File[] files = null;
                    Log.i("9527","_currentFolder\n"+_currentFolder!=null?_currentFolder.getName():"file is null");
                    if (_currentFolder.isDirectory())
                    {
                        files =  _currentFolder.listFiles() ;
                        if(files!=null) {
                            for (File f : files) {
                                Log.i("9527","_adapterData.add(f)"+f.getAbsolutePath());
                                _adapterData.add(f);
                            }
                        }else{

                        }
                    }
                    try {
                        Collections.sort(_adapterData, FileItemAdapter.this);
                    } catch (IllegalArgumentException ignored) {
                    }

                    if (canGoUp(_currentFolder))
                    {
                        _adapterData.add(0, _currentFolder.equals(new File("/storage/emulated/0")) ? new File("/storage/emulated") : _currentFolder.getParentFile());
                    }
                    handler.post(() -> {
                        notifyDataSetChanged();
                    });
                    Log.i("9527","loadFolder end _adapterData:\n"+_adapterData);
                }
            }
        };
        t.start();
    }
    public boolean canGoUp(File currentFolder) {
        File parentFolder = _currentFolder != null ? _currentFolder.getParentFile() : null;
        return parentFolder != null && (!_dopt.mustStartWithRootFolder || parentFolder.getAbsolutePath().startsWith(_dopt.rootFolder.getAbsolutePath()));
    }

    @Override
    public int compare(File o1, File o2) {
        if (o1 == null || o2 == null) {
            return 0;
        }
        if (o1.isDirectory() && _dopt.folderFirst)
            return o2.isDirectory() ? o1.getName().toLowerCase(Locale.getDefault()).compareTo(o2.getName().toLowerCase(Locale.getDefault())) : -1;
        else if (o2.isDirectory() && _dopt.folderFirst)
            return 1;
        else if (_dopt.fileComparable != null) {
            int v = _dopt.fileComparable.compare(o1, o2);
            if (v != 0) {
                return v;
            }
        }
        return o1.getName().toLowerCase(Locale.getDefault()).compareTo(o2.getName().toLowerCase(Locale.getDefault()));
    }
}
